﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BrnMall.Core;
using BrnMall.Manager.Domain.Distribution;
using BrnMall.Manager.Manager.Distribution;
using BrnMall.Services.Redlock;
using StackExchange.Redis;

namespace BrnMall.Services
{
    public static class Distributors
    {
        private const string GetDistributorAndCreateResourceName = "Lock-Key-GetDistributorAndCreate";

        /// <summary>
        /// 对订单进行利润分成
        /// </summary>
        /// <param name="order"></param>
        public static void CaculateBrokerage(OrderInfo order)
        {
            lock (GetDistributorAndCreateResourceName)
            {
                try
                {
                    if (BrokerageManager.CheckBrokerage(order.OSN))
                    {
                        Trace.TraceInformation($"订单编号{order.OSN}已发生过一次结算");
                        return;
                    }
                    var dis = DistributorManager.GetDistributorByUserId(order.Uid);
                    if (dis == null || dis.IsAgent == 1)
                    {
                        Trace.TraceInformation("没开通或者代理商交易不算提成");
                        return;
                    }

                    if (dis.AgentDId > 0)
                    {
                        var agent = DistributorManager.GetDistributor(dis.AgentDId);//代理商
                        var agentGrade = DistributorManager.GetGrade(agent.GradeId);

                        #region 添加代理商佣金明细

                        if (agent.Id > 0 && agent.Status != 2)
                        {
                            var agentBrokerageAmount = order.SurplusMoney * agentGrade.FirstBrokerageRise / 100;
                            if (agentBrokerageAmount <= 0.01M && agentBrokerageAmount > 0)
                            {
                                agentBrokerageAmount = 0.01M;
                            }
                            var agentBro = new Brokerage
                            {
                                ApprovedTime = DateTime.Now,
                                ApprovedUserId = 0,
                                ApprovedUserName = string.Empty,
                                BrokerageAmount = agentBrokerageAmount,
                                BrokerageType = 0,
                                OrderAmount = order.SurplusMoney,
                                OrderNo = order.OSN,
                                Remark = "订单支付成功，结算佣金",
                                Status = 1,
                                StoreId = order.StoreId,
                                TradeTime = DateTime.Now,
                                TradeUserId = order.Uid,
                                UserId = agent.UserId,
                                BrokerageRise = agentGrade.FirstBrokerageRise
                            };
                            BrokerageManager.AddBrokerageAndCaculate(agentBro);
                            Trace.TraceInformation("代理商分销计算提成结束");
                        }

                        #endregion 添加代理商佣金明细
                    }
                    //if (dis.ParentId == 0)
                    //{
                    //    Trace.TraceInformation("无上级分销不计算提成");
                    //    return;
                    //}

                    //var firstDis = DistributorManager.GetDistributor(dis.ParentId);//一级分销
                    //var firstdisGrade = DistributorManager.GetGrade(firstDis.GradeId);
                    var firstDis = dis;//下单人就是一级分销
                    var firstdisGrade = DistributorManager.GetGrade(firstDis.GradeId);

                    #region 添加一级佣金明细

                    var brokerageAmount = order.SurplusMoney * firstdisGrade.FirstBrokerageRise / 100;
                    if (brokerageAmount <= 0.01M && brokerageAmount > 0)
                    {
                        brokerageAmount = 0.01M;
                    }
                    if (firstDis.Status != 2)
                    {
                        var bro = new Brokerage
                        {
                            ApprovedTime = DateTime.Now,
                            ApprovedUserId = 0,
                            ApprovedUserName = string.Empty,
                            BrokerageAmount = brokerageAmount,
                            BrokerageType = 0,
                            OrderAmount = order.SurplusMoney,
                            OrderNo = order.OSN,
                            Remark = "订单支付成功，结算本店铺佣金",
                            Status = 1,
                            StoreId = order.StoreId,
                            TradeTime = DateTime.Now,
                            TradeUserId = order.Uid,
                            UserId = firstDis.UserId,
                            BrokerageRise = firstdisGrade.FirstBrokerageRise
                        };

                        BrokerageManager.AddBrokerageAndCaculate(bro);
                        Trace.TraceInformation("一级分销计算提成结束");
                    }

                    #endregion 添加一级佣金明细

                    if (firstDis.ParentId > 0)
                    {
                        var secondDis = DistributorManager.GetDistributor(firstDis.ParentId);//二级分销

                        #region 添加二级佣金明细

                        if (secondDis.Id > 0 && secondDis.Status != 2)
                        {
                            var secondBrokerageAmount = order.SurplusMoney * firstdisGrade.SecondBrokerageRise / 100;
                            if (secondBrokerageAmount <= 0.01M && secondBrokerageAmount > 0)
                            {
                                secondBrokerageAmount = 0.01M;
                            }
                            var secondBro = new Brokerage
                            {
                                ApprovedTime = DateTime.Now,
                                ApprovedUserId = 0,
                                ApprovedUserName = string.Empty,
                                BrokerageAmount = secondBrokerageAmount,
                                BrokerageType = 0,
                                OrderAmount = order.SurplusMoney,
                                OrderNo = order.OSN,
                                Remark = "订单支付成功，结算上一级佣金",
                                Status = 1,
                                StoreId = order.StoreId,
                                TradeTime = DateTime.Now,
                                TradeUserId = order.Uid,
                                UserId = secondDis.UserId,
                                BrokerageRise = firstdisGrade.SecondBrokerageRise
                            };
                            BrokerageManager.AddBrokerageAndCaculate(secondBro);
                            Trace.TraceInformation("二级分销计算提成结束");
                        }

                        #endregion 添加二级佣金明细

                        if (secondDis.ParentId > 0)
                        {
                            var thirdDis = DistributorManager.GetDistributor(secondDis.ParentId);//三级分销

                            #region 添加三级佣金明细

                            if (thirdDis.Id > 0 && thirdDis.Status != 2)
                            {
                                var thirdBrokerageAmount = order.SurplusMoney * firstdisGrade.ThirdBrokerageRise / 100;
                                if (thirdBrokerageAmount <= 0.01M && thirdBrokerageAmount > 0)
                                {
                                    thirdBrokerageAmount = 0.01M;
                                }
                                var thirdBro = new Brokerage
                                {
                                    ApprovedTime = DateTime.Now,
                                    ApprovedUserId = 0,
                                    ApprovedUserName = string.Empty,
                                    BrokerageAmount = thirdBrokerageAmount,
                                    BrokerageType = 0,
                                    OrderAmount = order.SurplusMoney,
                                    OrderNo = order.OSN,
                                    Remark = "订单支付成功，结算上二级佣金",
                                    Status = 1,
                                    StoreId = order.StoreId,
                                    TradeTime = DateTime.Now,
                                    TradeUserId = order.Uid,
                                    UserId = thirdDis.UserId,
                                    BrokerageRise = firstdisGrade.ThirdBrokerageRise
                                };
                                BrokerageManager.AddBrokerageAndCaculate(thirdBro);
                                Trace.TraceInformation("三级分销计算提成结束");
                            }

                            #endregion 添加三级佣金明细
                        }
                    }
                }
                catch (Exception e)
                {
                    Trace.TraceError(e.Message);
                    Trace.TraceError(e.Source);
                }
            }
        }

        public static Distributor GetDistributorAndCreate(int userId, int storeId, int disId = 0, int agentId = 0)
        {
            Trace.TraceInformation("GetDistributorAndCreate");
            //var dlm = new Redlock.Redlock(ConnectionMultiplexer.Connect(ConfigurationManager.AppSettings["RedisConn"]));
            //Lock lockObject;
            //dlm.Lock(GetDistributorAndCreateResourceName, new TimeSpan(0, 0, 10), out lockObject);//分布式锁
            Trace.TraceInformation("启用分布式锁");
            var dis = DistributorManager.GetDistributorByUserId(userId) ?? CreateDefaultDistritor(userId, storeId, disId, agentId);
            var parentDis = DistributorManager.GetDistributor(disId);
            //分销商分享
            if (parentDis != null && parentDis.IsAgent == 0)
            {
                Trace.TraceInformation("分销商分享");
                if (dis.IsAgent == 0
                    && dis.ParentId == 0
                    && disId != dis.Id
                    && !DistributorManager.IsChildDistributor(disId, dis.Id)
                    && DistributorManager.GetChildDistributors(dis.Id, false).Count == 0)//已结有团队的分销商不能成为别人的下级
                {
                    dis.ParentId = disId;
                    dis.Path = parentDis.Path + parentDis.Id + "|";
                    var arrayPath = dis.Path.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    if (arrayPath.Length == 3)
                    {
                        dis.Path = $"{arrayPath[1]}|{arrayPath[2]}|";
                    }
                }
                if (dis.IsAgent == 0 && agentId != 0 && dis.AgentDId == 0 && agentId != dis.Id)
                {
                    var parentAgent = DistributorManager.GetDistributor(agentId);
                    if (parentAgent != null)
                        dis.AgentDId = agentId;
                }
            }
            //代理商分享
            if (disId == 0 && dis.IsAgent == 0 && agentId != 0 && dis.AgentDId == 0 && agentId != dis.Id)
            {
                Trace.TraceInformation("代理商分享");
                var parentAgent = DistributorManager.GetDistributor(agentId);
                if (parentAgent != null)
                    dis.AgentDId = agentId;
            }
            DistributorManager.UpdateDistributor(dis);
            //dlm.Unlock(lockObject);//释放分布式锁
            return dis;
        }

        /// <summary>
        /// 开通分销商功能
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="storeId">店铺ID</param>
        /// <param name="parentDId">上级分销商ID，</param>
        /// <param name="agentDId">上级代理商ID，通过首页参数获取：/pages/index/index?agentId=1&disId=1</param>
        /// <returns></returns>
        public static Distributor CreateDefaultDistritor(int userId, int storeId, int parentDId = 0, int agentDId = 0)
        {
            var user = Users.GetPartUserById(userId);
            if (user == null)
                throw new Exception("UserId不存在");
            var dis = new Distributor();
            var ifexist = DistributorManager.GetDistributorByUserId(userId);
            if (ifexist != null && ifexist.IsAgent == 1)
                throw new Exception("代理商不能开通分销功能");
            if (ifexist != null) return ifexist;
            dis.IsAgent = 0;
            dis.UserId = userId;
            var defaultGrade = DistributorManager.GetGradeDefault(storeId, 0);
            dis.GradeId = defaultGrade.Id;
            dis.ShowLogo = user.Avatar;
            dis.Status = 1;
            dis.StoreId = storeId;
            dis.CreateTime = DateTime.Now;
            dis.LinkMan = user.NickName;
            dis.DisStoreName = user.NickName;
            dis.PhoneNumber = user.Mobile;

            if (dis.StoreId == 0)
                throw new Exception("当前登录用户的所属店铺不正确:0");
            DistributorManager.AddDistributor(dis);
            return dis;
        }

        public static string GetDistributorSet(int storeId)
        {
           var model=DistributorManager.GetDisConfig(storeId);
            if (model == null)
                throw new Exception("分销未设置。");
            return model.CardSlogan; 
        }

    }
}